/**
 * Base 控制器
 */
import jwt from "jsonwebtoken"
import { writeLog } from "../../utils/utils"
const SECRET = "xinxing_taiqiu@dev"
const randomNumber = toString(Math.floor(Math.random() * 10000))
const tokenKey = SECRET + randomNumber

export default class BaseController {
  constructor() {
    this.createToken = this.createToken.bind(this)
    this.verifyTokenMiddle = this.verifyTokenMiddle.bind(this)
    this.state = {
      userInfo: null
    }
  }

  /**
   * 生成用户token
   * @param {String} userId 用户id
   * @returns Object
   */
  createToken (userId) {
    const payload = {
      id: String(userId),
    }
    return jwt.sign(payload, tokenKey, { expiresIn: "6h" }) //'10s', "10h", "7d".
  }

  /**
   * 验证token
   * @param {String} token 根据id生成的用户token
   * @returns Object {id:1,...} id为用户id
   */
  async verifyTokenMiddle (token, response) {
    return new Promise((resolve, reject) => {
      return jwt.verify(token, tokenKey, async (err, decoded) => {
        if (err) {
          if (/expired/.test(err.message) || err.message === "jwt expired") {
            resolve({ status: -2, msg: "登录状态过期" })
            return
          }
          resolve({ status: -2, msg: "token验证失败" })
          return
        }
        const _checkUserExist = await this.checkUserExist(decoded.id, response)
        if (_checkUserExist) {
          this.state.userInfo = _checkUserExist
          resolve({ ...decoded, ..._checkUserExist })
        }
      })
    })
  }

  // 校验用户是否存在
  async checkUserExist (user_id, response) {
    const sql1 = "select * from tq_user where user_id = ?"
    const resultUserInfo = await global.query(sql1, response, [user_id])
    if (this.isEmpty(resultUserInfo)) {
      response.json({ code: -3, msg: "用户不存在" })
      return false
    }
    return resultUserInfo[0]
  }

  // 返回用户id，如果是管理员直接返回管理员user_id，否则返回其父级id
  getUserid () {
    const { userInfo } = this.state
    let user_id = userInfo.user_id
    // 非管理员用户，取其父级id
    if (userInfo.user_state === 0) {
      user_id = userInfo.user_parent_id
    }
    return user_id
  }

  /**
   * 分页查询控制器
   * @param {Object} opts
   * @param {Object} opts.request 请求体参数
   * @param {Object} opts.response 相应体
   * @param {Object} opts.params 查询参数
   * @param {Object} opts.total_sql 查询总数的sql
   * @param {Object} opts.paging_sql 查询分页的sql
   * @returns
   */
  async pagingController (opts) {
    const { request, response, params, total_sql, paging_sql } = opts
    try {
      let { page, pageSize } = request.query
      if (this.isEmpty(page)) {
        page = 1
      }

      if (this.isEmpty(pageSize)) {
        pageSize = 12
      }
      pageSize = parseInt(pageSize)

      //查总条数
      let totalResult = await global.query(total_sql, response, params)

      //分页查询
      let start = (page - 1) * pageSize
      let pagingResult = await global.query(
        paging_sql + ` ${start},${pageSize}`,
        response,
        params
      )
      // console.log('----------------------------')
      // console.log('start',start)

      // 计算总页数
      let allCount = totalResult[0].total
      let allPage = parseInt(allCount) / pageSize
      let pageStr = allPage.toString()
      // 不能被整除
      if (pageStr.indexOf(".") > 0) {
        allPage = parseInt(pageStr.split(".")[0]) + 1
      }

      if (this.isEmpty(pagingResult)) {
        response.json({
          code: 1,
          msg: "获取成功",
          data: {
            list: [],
            page: parseInt(page),
            pageSize: pageSize,
            pageCount: allPage,
            total: allCount,
          },
        })
        return
      }

      return {
        list: pagingResult,
        page: parseInt(page),
        pageSize: pageSize,
        pageCount: allPage,
        total: allCount,
      }
    } catch (error) {
      writeLog("[pagingController error]" + error)
      response.json({ code: 500, msg: error })
    }
  }

  /**
   * 是否为空
   * @param {String | Object | Array} str
   */
  isEmpty (str) {
    return (
      str == null ||
      str == "" ||
      str == undefined ||
      str == "undefined" ||
      str.length == 0
      // JSON.stringify(str) == "{}"
    )
  }
}
